package com.qst.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qst.domain.VipLedger;
import com.qst.domain.VipUser;
import com.qst.dto.Result;
import com.qst.dto.UserDTO;
import com.qst.mapper.VipUserMapper;
import com.qst.service.IVipUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;

@Service
public class VipUserServiceImpl extends ServiceImpl<VipUserMapper, VipUser> implements IVipUserService {

    @Autowired
    private RestTemplate restTemplate;

    @Override
    @Transactional
    public Result saveVipUser(VipUser vipUser) {
        // 更新数据库
        boolean success = save(vipUser);
        if (!success) {
            return Result.fail("新增会员失败！");
        }
        return Result.ok("新增会员成功！");
    }

    @Override
    @Transactional
    public Result updateVipUser(VipUser vipUser) {
        Long id = vipUser.getVipId();
        if (id == null) {
            return Result.fail("会员id不能为空！");
        }
        // 1.更新数据库
        updateById(vipUser);
        return Result.ok("更新成功！");
    }

    @Override
    @Transactional
    public Result updateUserById(UserDTO userDTO) {
        Long vipId = userDTO.getVipId();
        float point = userDTO.getPoint();
        boolean isSuccess = update().set("point", point).eq("vip_id", vipId).update();
        if (!isSuccess) {
            return Result.fail("更新积分余额失败");
        }
        return Result.fail("更新积分余额成功");
    }

    @Override
    public Result deleteVipUserById(Long id) {
        boolean isSuccess = remove(new QueryWrapper<VipUser>()
                .eq("vip_id", id));
        if (!isSuccess) {
            return Result.fail("删除失败！");
        }
        return Result.ok("删除成功！");
    }



    @Override
    public Result findVipUserPointById(Long id) {
        VipUser vipUser = getById(id);
        if (vipUser == null) {
            return Result.fail("此用户不存在！");
        }
        String point = vipUser.getPoint();
        return Result.ok(point);
    }

    @Override
    public Result findVipUserLedgerById(Long id) {

        // 1.利用RestTemplate发起http请求，查询用户
        // 1.1url路径
        String url = "http://point-service/ledger/" + id;
        VipLedger[] ledgers = restTemplate.getForObject(url, VipLedger[].class);
        if (ledgers == null){
            return Result.fail("获取台账错误");
        }
        List<VipLedger> vipLedgers = new ArrayList<>();
        for (VipLedger ledger : ledgers) {
            System.out.println(ledger);
            vipLedgers.add(ledger);
        }
        return Result.ok(vipLedgers,vipLedgers.stream().count());
    }

}
